package com.wt.springsamples.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wt.springsamples.common.BizException;
import com.wt.springsamples.model.Org;
import com.wt.springsamples.biz.mybatis.mapper.OrgMapper;
import com.wt.springsamples.model.dto.OrgTreeNode;
import com.wt.springsamples.biz.service.IOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper,Org> implements IOrgService {

    @Autowired
    private OrgMapper orgMapper;


    @Override
    public List<OrgTreeNode> getOrgTreeNodeList() {
        List<Org> allOrgList = orgMapper.selectList(new QueryWrapper<>());
        List<OrgTreeNode>  treeNodeList = convertListBy(allOrgList);
        return list2Tree(treeNodeList,null);
    }


    @Override
    public OrgTreeNode getOrgTreeNodeInfo(long orgId) {

        List<Org> allOrgList = orgMapper.selectList(new QueryWrapper<>());
        Org org = findOrgById(allOrgList,orgId);
        if(org == null){
            throw new BizException(50001,"数据不存在");
        }
        List<OrgTreeNode> children = list2Tree(convertListBy(allOrgList),org.getId());
        OrgTreeNode node = new OrgTreeNode();
        node.setId(org.getId());
        node.setName(org.getName());
        node.setPid(org.getPid());
        node.setChildren(children);
        return node;
    }

    private List<OrgTreeNode> list2Tree( List<OrgTreeNode> nodeList,Long pid){
        List<OrgTreeNode> children = new ArrayList<>();
        for(OrgTreeNode node:nodeList){
            if(node.getPid() == pid){
                node.setChildren(list2Tree(nodeList,node.getId()));
                children.add(node);
            }
        }
        return  children;
    }

    private List<OrgTreeNode> convertListBy(List<Org> orgList){
        List<OrgTreeNode>  list = orgList.stream().map((org)->{
            OrgTreeNode treeNode = new OrgTreeNode();
            treeNode.setId(org.getId());
            treeNode.setName(org.getName());
            treeNode.setPid(org.getPid());
            return treeNode;
        }).collect(Collectors.toList());
        return list;
    }

    private  Org findOrgById(List<Org> orgList,long orgId){
        for(Org org:orgList){
            if(orgId==org.getId()){
              return org;
            }
        }
        return null;
    }

    private List<Org> findListByPid(List<Org> orgList,long pid){
        List<Org> children = new ArrayList<>();
        for(Org org:orgList){
            if(pid==org.getPid()){
                children.add(org);
            }
        }
        return children;
    }
}
